package com.canyou.service;

import com.canyou.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 登录失败次数处理
 *
 * @author cc
 * @author 2019-06-13
 */
@Service
@Slf4j
public class LoginAttemptService {
    /**
     * 锁定的用户自动解锁的时间，单位分钟
     */
    public final int catchExpire = 300;
    /**
     * 连续错误次数
     */
    private final int MAX_ATTEMPT = 5;

    private final String keyPart = "login_fail_times-";

    public LoginAttemptService() {
    }

    public void loginSucceeded(String key) {
        RedisUtils.del(keyPart + key);
    }

    /**
     * 记录登记失败次数
     *
     * @param key
     */
    public void loginFailed(String key) {
        int attempts = getAttempts(key);
        attempts++;
        RedisUtils.set(keyPart + key, attempts, catchExpire);
    }

    /**
     * 判断是否锁定该用户
     *
     * @return boolean
     * @Param key
     **/
    public boolean isLocked(String key) {
        int attempts = getAttempts(key);
        return attempts >= MAX_ATTEMPT;
    }

    public int getAttempts(String key) {
        try {
            Object value = RedisUtils.get(keyPart + key);
            if (value != null) {
                return Integer.parseInt(value.toString());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return 0;
    }

    public long fail(String key) {
        final String newKey = keyPart + key;
        if (RedisUtils.hasKey(newKey)) {
            return RedisUtils.incr(newKey, 1L);
        } else {
            RedisUtils.set(newKey, 1L, catchExpire);
            return 1L;
        }
    }

    public int leftCount(String key) {
        return MAX_ATTEMPT - getAttempts(key);
    }

}
